package cn.dengta.webapp.user.module.file;

import java.io.File;
import java.io.IOException;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import javax.imageio.ImageIO;

import cn.dengta.context.model.Member;
import cn.dengta.webapp.base.entity.BaseEntity;

public abstract class FileManagerUtil {

	public static final String FIELD_DIR_PREFIX = "dirPrefix";
	public static final String FIELD_PREFIX = "prefix";

	public static final Map<String, String> buildContext(@Nullable Map<String, String> context, Member user, Boolean isPublic) {
		if (context == null) {
			context = new HashMap<>(4);
		}
		if (user != null) {
			context.put(FileManagerUtil.FIELD_PREFIX, BaseEntity.id2Alias(user.getId()).concat("-"));
		}
		if (isPublic != null) {
			context.put(FileManagerUtil.FIELD_DIR_PREFIX, isPublic ? "public/" : "private/");
		}
		return context;
	}

	public static String buildNewFileName(String namePattern, String fileName, Map<String, String> context) {
		return new FileNameBuilder(namePattern).build(fileName, null, context);
	}

	/**
	 * 检测指定文件是否是真实的图片文件
	 */
	public static boolean isRealImage(File file) {
		try {
			return ImageIO.read(file) != null;
		} catch (IOException e) {
			return false;
		}
	}

	/**
	 * 根据文件名获取对应的内容类型（MIME）
	 */
	public static String calcMIMETypeByName(String filename) {
		return URLConnection.guessContentTypeFromName(filename);
	}

}
